package com.first.module.acm.action;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;

import com.first.core.Constants;
import com.first.core.common.QueryFilter;
import com.first.core.util.AppUtil;
import com.first.core.util.BeanUtil;
import com.first.core.util.ContextUtil;
import com.first.core.util.JsonUtil;
import com.first.core.util.PagingBean;
import com.first.core.util.StringUtil;
import com.first.core.web.action.BaseAction;
import com.first.module.acm.model.AppRole;
import com.first.module.acm.model.AppUser;
import com.first.module.acm.model.Department;
import com.first.module.acm.model.OnlineUser;
import com.first.module.acm.service.AppRoleService;
import com.first.module.acm.service.AppUserService;
import com.first.module.acm.service.DepartmentService;
import com.first.module.acm.service.UserSubService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import flexjson.DateTransformer;
import flexjson.JSONSerializer;

public class AppUserAction extends BaseAction {

	private static String SUPPER_MANAGER_ID = "";
	@Resource
	private AppUserService appUserService;
	@Resource
	private AppRoleService appRoleService;
	@Resource
	private UserSubService userSubService;
	@Resource
	private DepartmentService departmentService;
	private AppUser appUser;
	private String userId;
	private String depId;
	private String roleId;

	public AppUserAction() {
	}

	public String getDepId() {
		return depId;
	}

	public void setDepId(String depId) {
		this.depId = depId;
	}

	public String getRoleId() {
		return roleId;
	}

	public void setRoleId(String roleId) {
		this.roleId = roleId;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public AppUser getAppUser() {
		return appUser;
	}

	public void setAppUser(AppUser appUser) {
		this.appUser = appUser;
	}

	public String getCurrent() {
		AppUser currentUser = ContextUtil.getCurrentUser();
		Iterator publicIds = AppUtil.getPublicMenuIds().iterator();
		StringBuffer publicIdSb = new StringBuffer();
		for (; publicIds.hasNext();) {
			publicIdSb.append(",").append((String) publicIds.next());
		}
		// List list = indexDisplayService.findByUser(currentUser.getUserId());
		List items = new ArrayList();
		// PanelItem pi;
		// for(Iterator iterator = list.iterator(); iterator.hasNext();
		// items.add(pi))
		// {
		// IndexDisplay id = (IndexDisplay)iterator.next();
		// pi = new PanelItem();
		// pi.setPanelId(id.getPortalId());
		// pi.setColumn(id.getColNum().intValue());
		// pi.setRow(id.getRowNum().intValue());
		// }

		String superId = null;
		String superior = "";
		List<String> superiors = userSubService.upUser(currentUser.getUserId());
		if (superiors != null && superiors.size() > 0) {
			superId = superiors.get(0);
			AppUser user = (AppUser) appUserService.get(superId);
			superior = user.getFullname();
		}

		StringBuffer sb = new StringBuffer();
		sb.append("{success:true,user:{userId:'").append(
				currentUser.getUserId()).append("',fullname:'").append(
				currentUser.getFullname()).append("',superId:'")
				.append(superId).append("',superior:'").append(superior)
				.append("',rights:'");
		sb.append(currentUser.getRights().toString().replace("[", "").replace(
				"]", ""));
		if (!"".equals(currentUser.getRights()) && publicIdSb.length() > 0) {
			sb.append(publicIdSb.toString());
		}
		Gson gson = new Gson();
		sb.append("',items:").append(gson.toJson(items).toString());
		sb.append("}}");
		setJsonString(sb.toString());
		return "success";
	}

	public String list() {
		QueryFilter filter = new QueryFilter(getRequest());
		filter
				.addFilter("Q_delFlag_SN_EQ", Constants.FLAG_UNDELETED
						.toString());
		List list = appUserService.getAll(filter);
		StringBuffer buff = (new StringBuffer("{success:true,'totalCounts':"))
				.append(filter.getPagingBean().getTotalItems()).append(
						",result:");
		JSONSerializer serializer = new JSONSerializer();
		serializer.transform(new DateTransformer("yyyy-MM-dd"),
				new String[] { "accessionTime" });
		buff.append(serializer.exclude(new String[] { "password" }).serialize(
				list));
		buff.append("}");
		jsonString = buff.toString();
		return "success";
	}

	public String online() {
		Map onlineUsers = new HashMap();
		Map onlineUsersByDep = new HashMap();
		Map onlineUsersByRole = new HashMap();
		onlineUsers = AppUtil.getOnlineUsers();
		if (depId != null) {
			for (Iterator iterator = onlineUsers.keySet().iterator(); iterator
					.hasNext();) {
				String sessionId = (String) iterator.next();
				OnlineUser onlineUser = new OnlineUser();
				onlineUser = (OnlineUser) onlineUsers.get(sessionId);
				String path = "";
				if (!onlineUser.getUserId().equals(AppUser.SUPER_USER)) {
					path = onlineUser.getDepPath();
				}
				if (!depId.equals(new Long(0L))) {
					if (Pattern.compile(
							(new StringBuilder(".")).append(depId).append(".")
									.toString()).matcher(path).find()) {
						onlineUsersByDep.put(sessionId, onlineUser);
					}
				} else {
					onlineUsersByDep.put(sessionId, onlineUser);
				}
			}

		}
		if (roleId != null) {
			for (Iterator iterator1 = onlineUsers.keySet().iterator(); iterator1
					.hasNext();) {
				String sessionId = (String) iterator1.next();
				OnlineUser onlineUser = new OnlineUser();
				onlineUser = (OnlineUser) onlineUsers.get(sessionId);
				if (Pattern.compile(
						(new StringBuilder(",")).append(roleId).append(",")
								.toString()).matcher(onlineUser.getRoleIds())
						.find()) {
					onlineUsersByRole.put(sessionId, onlineUser);
				}
			}

		}
		Type type = new TypeToken<Collection<OnlineUser>>() {
		}.getType();
		StringBuffer buff = (new StringBuffer("{success:true,'totalCounts':"))
				.append(onlineUsers.size()).append(",result:");
		Gson gson = new Gson();
		if (depId != null) {
			buff.append(gson.toJson(onlineUsersByDep.values(), type));
		} else if (roleId != null) {
			buff.append(gson.toJson(onlineUsersByRole.values(), type));
		} else {
			buff.append(gson.toJson(onlineUsers.values(), type));
		}
		buff.append("}");
		jsonString = buff.toString();
		return "success";
	}

	public String find() {
		String strRoleId = getRequest().getParameter("roleId");
		PagingBean pb = getInitPagingBean();
		if (StringUtils.isNotEmpty(strRoleId)) {
			List<AppUser> userList = appUserService.findByRole(Long
					.valueOf(Long.parseLong(strRoleId)), pb);
			Type type = new TypeToken<List<AppUser>>() {
			}.getType();
			StringBuffer buff = (new StringBuffer(
					"{success:true,'totalCounts':")).append(pb.getTotalItems())
					.append(",result:");
			Gson gson = (new GsonBuilder())
					.excludeFieldsWithoutExposeAnnotation().create();
			buff.append(gson.toJson(userList, type));
			buff.append("}");
			jsonString = buff.toString();
		} else {
			jsonString = "{success:false}";
		}
		return "success";
	}

	public String multiDel() {
		String ids[] = getRequest().getParameterValues("ids");
		StringBuffer buff = new StringBuffer("{success:true");
		if (ids != null) {
			buff.append(",msg:'");
			String as[];
			int j = (as = ids).length;
			for (int i = 0; i < j; i++) {
				String id = as[i];
				AppUser delUser = (AppUser) appUserService.get(id);
				AppRole superManager = (AppRole) appRoleService
						.get(SUPPER_MANAGER_ID);
				if (delUser.getRoles().contains(superManager)) {
					buff
							.append("\u5458\u5DE5:")
							.append(delUser.getUsername())
							.append(
									"\u662F\u8D85\u7EA7\u7BA1\u7406\u5458,\u4E0D\u80FD\u5220\u9664!<br><br/>");
				} else if (delUser.getUserId().equals(
						ContextUtil.getCurrentUserId())) {
					buff
							.append("\u4E0D\u80FD\u5220\u9664\u81EA\u5DF1!<br></br>");
				} else {
					delUser.setStatus(Constants.FLAG_DISABLE);
					delUser.setDelFlag(Constants.FLAG_DELETED);
					delUser.setUsername((new StringBuilder("__")).append(
							delUser.getUsername()).toString());
					appUserService.save(delUser);
				}
			}

			buff.append("'");
		}
		buff.append("}");
		setJsonString(buff.toString());
		return "success";
	}

	public String get() {
		AppUser appUser = null;
		JSONSerializer json = JsonUtil
				.getJSONSerializer(new String[] { "accessionTime" });
		if (userId != null) {
			appUser = (AppUser) appUserService.get(userId);
		} else {
			json.exclude(new String[] { "accessionTime", "department",
					"password", "status", "position" });
			appUser = ContextUtil.getCurrentUser();
		}
		StringBuffer sb = new StringBuffer("{success:true,totalCounts:1,data:[");
		sb.append(JsonUtil.getJSONSerializer(new String[] { "accessionTime" })
				.serialize(appUser));
		sb.append("]}");
		setJsonString(sb.toString());
		return "success";
	}

	public String save() {
		String rolesIds = getRequest().getParameter("AppUserRoles");
		String ids[] = rolesIds.split(",");
		Set roles = new HashSet();
		String as[];
		int j = (as = ids).length;
		for (int i = 0; i < j; i++) {
			String id = as[i];
			if (!"".equals(id)) {
				AppRole role = (AppRole) appRoleService.get(id);
				roles.add(role);
			}
		}

		appUser.setRoles(roles);
		if (appUser.getUserId() != null && appUser.getUserId().equals("")) {
			appUser.setUserId(null);
		}
		if (appUser.getUserId() != null && !appUser.getUserId().equals("")) {
			AppUser old = (AppUser) appUserService.get(appUser.getUserId());
			appUser.setDelFlag(old.getDelFlag());
			appUser.setPassword(old.getPassword());
			appUserService.merge(appUser);
			setJsonString("{success:true}");
		} else if (appUserService.findByUserName(appUser.getUsername()) == null) {
			appUser.setDelFlag(Constants.FLAG_UNDELETED);
			appUser
					.setPassword(StringUtil
							.encryptSha256(appUser.getPassword()));
			appUserService.merge(appUser);
			setJsonString("{success:true}");
		} else {
			setJsonString((new StringBuilder(
					"{success:false,msg:'\u7528\u6237\u767B\u5F55\u8D26\u53F7:"))
					.append(appUser.getUsername())
					.append(
							"\u5DF2\u5B58\u5728,\u8BF7\u91CD\u65B0\u8F93\u5165\u8D26\u53F7.'}")
					.toString());
		}
		return "success";
	}

	public String selectedRoles() {
		if (userId != null && !userId.equals("")) {
			setAppUser((AppUser) appUserService.get(userId));
			Set roles = appUser.getRoles();
			StringBuffer sb = new StringBuffer("[");
			AppRole role;
			for (Iterator iterator = roles.iterator(); iterator.hasNext(); sb
					.append((new StringBuilder("['")).append(role.getRoleId())
							.append("','").append(role.getRoleName()).append(
									"'],").toString())) {
				role = (AppRole) iterator.next();
			}

			sb.deleteCharAt(sb.length() - 1);
			sb.append("]");
			setJsonString(sb.toString());
		}
		return "success";
	}

	public String chooseRoles() {
		List chooseRoles = appRoleService.getAll();
		if (userId != null && !userId.equals("")) {
			setAppUser(appUserService.get(userId));
			Set selectedRoles = appUser.getRoles();
			AppRole role;
			for (Iterator iterator = selectedRoles.iterator(); iterator
					.hasNext(); chooseRoles.remove(role)) {
				role = (AppRole) iterator.next();
			}

		}
		StringBuffer sb = new StringBuffer("[");
		for (Iterator iterator1 = chooseRoles.iterator(); iterator1.hasNext();) {
			AppRole role = (AppRole) iterator1.next();
			if (role.getStatus().shortValue() != 0) {
				sb.append((new StringBuilder("['")).append(role.getRoleId())
						.append("','").append(role.getRoleName()).append("'],")
						.toString());
			}
		}

		sb.deleteCharAt(sb.length() - 1);
		sb.append("]");
		setJsonString(sb.toString());
		return "success";
	}

	public String resetPassword() {
		String userId = getRequest().getParameter("appUserUserId");
		String oldPassword = StringUtil.encryptSha256(getRequest()
				.getParameter("oldPassword"));
		String newPassword = getRequest().getParameter("newPassword");
		String againPassword = getRequest().getParameter("againPassword");
		if (StringUtils.isNotEmpty(userId)) {
			setAppUser((AppUser) appUserService.get(userId));
		} else {
			setAppUser(ContextUtil.getCurrentUser());
		}
		StringBuffer msg = new StringBuffer("{msg:'");
		boolean pass = false;
		if (oldPassword.equals(appUser.getPassword())) {
			if (newPassword.equals(againPassword)) {
				pass = true;
			} else {
				msg.append("\u4E24\u6B21\u8F93\u5165\u4E0D\u4E00\u81F4.'");
			}
		} else {
			msg.append("\u65E7\u5BC6\u7801\u8F93\u5165\u4E0D\u6B63\u786E.'");
		}
		if (pass) {
			appUser.setPassword(StringUtil.encryptSha256(newPassword));
			appUserService.save(appUser);
			setJsonString("{success:true}");
		} else {
			msg.append(",failure:true}");
			setJsonString(msg.toString());
		}
		return "success";
	}

	public String photo() {
		setAppUser((AppUser) appUserService.get(getUserId()));
		appUserService.save(appUser);
		return "success";
	}

	public String subAdepartment() {
		PagingBean pb = getInitPagingBean();
		String strDepId = getRequest().getParameter("depId");
		String path = "0.";
		// AppUser user = ContextUtil.getCurrentUser();
		String selectUserId = getRequest().getParameter("userId");
		AppUser user;
		if (selectUserId != null && !"".equals(selectUserId)) {
			user = appUserService.get(selectUserId);
		} else {
			user = ContextUtil.getCurrentUser();
		}
		if ("0.".equals(path)) {
			path = null;
		}
		String uId = user.getUserId();
		Set userIds = userSubService.findAllUpUser(uId);
		List userIdsL = userSubService.subUsers(uId);
		userIds.add(uId);
		Long l;
		for (Iterator iterator = userIdsL.iterator(); iterator.hasNext(); userIds
				.add(l)) {
			l = (Long) iterator.next();
		}

		List<AppUser> list = appUserService.findSubAppUser(path, userIds, pb);
		Type type = new TypeToken<List<AppUser>>() {
		}.getType();
		StringBuffer buff = (new StringBuffer("{success:true,'totalCounts':"))
				.append(pb.getTotalItems()).append(",result:");
		Gson gson = (new GsonBuilder()).excludeFieldsWithoutExposeAnnotation()
				.create();
		buff.append(gson.toJson(list, type));
		buff.append("}");
		jsonString = buff.toString();
		return "success";
	}

	public String subArole() {
		String strRoleId = getRequest().getParameter("roleId");
		PagingBean pb = getInitPagingBean();
		// AppUser user = ContextUtil.getCurrentUser();
		String selectUserId = getRequest().getParameter("userId");
		AppUser user;
		if (selectUserId != null && !"".equals(selectUserId)) {
			user = appUserService.get(selectUserId);
		} else {
			user = ContextUtil.getCurrentUser();
		}
		if (StringUtils.isNotEmpty(strRoleId)) {
			String uId = user.getUserId();
			Set userIds = userSubService.findAllUpUser(uId);
			List userIdsL = userSubService.subUsers(uId);
			userIds.add(uId);
			Long l;
			for (Iterator iterator = userIdsL.iterator(); iterator.hasNext(); userIds
					.add(l)) {
				l = (Long) iterator.next();
			}

			List<AppUser> userList = appUserService.findSubAppUserByRole(
					new Long(strRoleId), userIds, pb);
			Type type = new TypeToken<List<AppUser>>() {
			}.getType();
			StringBuffer buff = (new StringBuffer(
					"{success:true,'totalCounts':")).append(pb.getTotalItems())
					.append(",result:");
			Gson gson = (new GsonBuilder())
					.excludeFieldsWithoutExposeAnnotation().create();
			buff.append(gson.toJson(userList, type));
			buff.append("}");
			jsonString = buff.toString();
		} else {
			jsonString = "{success:false}";
		}
		return "success";
	}

	public String onlineAsub() {
		Map onlineUsers = new HashMap();
		Map onlineUsersBySub = new HashMap();
		onlineUsers = AppUtil.getOnlineUsers();
		// AppUser user = ContextUtil.getCurrentUser();
		String selectUserId = getRequest().getParameter("userId");
		AppUser user;
		if (selectUserId != null && !"".equals(selectUserId)) {
			user = appUserService.get(selectUserId);
		} else {
			user = ContextUtil.getCurrentUser();
		}
		String uId = user.getUserId();
		Set userIds = userSubService.findAllUpUser(uId);
		userIds.add(uId);
		List userIdsL = userSubService.subUsers(uId);
		Long l;
		for (Iterator iterator = userIdsL.iterator(); iterator.hasNext(); userIds
				.add(l)) {
			l = (Long) iterator.next();
		}

		for (Iterator iterator1 = onlineUsers.keySet().iterator(); iterator1
				.hasNext();) {
			String sessionId = (String) iterator1.next();
			OnlineUser onlineUser = new OnlineUser();
			onlineUser = (OnlineUser) onlineUsers.get(sessionId);
			if (!userIds.contains(onlineUser.getUserId())) {
				onlineUsersBySub.put(sessionId, onlineUser);
			}
		}

		Type type = new TypeToken<Map<String, OnlineUser>>() {
		}.getType();
		StringBuffer buff = (new StringBuffer("{success:true,'totalCounts':"))
				.append(onlineUsers.size()).append(",result:");
		Gson gson = new Gson();
		buff.append(gson.toJson(onlineUsersBySub.values(), type));
		buff.append("}");
		jsonString = buff.toString();
		return "success";
	}

	public String upUser() {
		List ids = userSubService.upUser(ContextUtil.getCurrentUserId());
		List list = new ArrayList();
		String l;
		for (Iterator iterator = ids.iterator(); iterator.hasNext(); list
				.add((AppUser) appUserService.get(l))) {
			l = (String) iterator.next();
		}

		StringBuffer buff = new StringBuffer("[");
		AppUser user;
		for (Iterator iterator1 = list.iterator(); iterator1.hasNext(); buff
				.append((new StringBuilder("['")).append(
						user.getUserId().toString()).append("','").append(
						user.getFullname()).append("'],").toString())) {
			user = (AppUser) iterator1.next();
		}

		if (list.size() > 0) {
			buff.deleteCharAt(buff.length() - 1);
		}
		buff.append("]");
		setJsonString(buff.toString());
		return "success";
	}

	public String profile() {
		AppUser old = ContextUtil.getCurrentUser();
		try {
			BeanUtil.copyNotNullProperties(old, appUser);
		} catch (Exception e) {
			logger.info(e);
		}
		appUserService.save(old);
		jsonString = "{success:true}";
		return "success";
	}

	// 用户密码初始化
	public String initializePassword() {
		String userId = getRequest().getParameter("appUserUserId");
		if (StringUtils.isNotEmpty(userId)) {
			setAppUser(appUserService.get(userId));
			appUser.setPassword(StringUtil.encryptSha256(Constants.PASSWORD));
			appUserService.save(appUser);
			setJsonString("{success:true}");
		} else {
			StringBuffer msg = new StringBuffer("{msg:'当前用户不存在！'");
			msg.append(",failure:true}");
			setJsonString(msg.toString());
		}
		return SUCCESS;
	}

	 public String select()
	    {
		 PagingBean pb = getInitPagingBean();   
		 List list = appUserService.getAll(pb);
        StringBuffer buff = (new StringBuffer("{success:true,'totalCounts':")).append(pb.getTotalItems()).append(",result:");
        JSONSerializer serializer = new JSONSerializer();
        serializer.transform(new DateTransformer("yyyy-MM-dd"), new String[] {
            "accessionTime"
        });
        buff.append(serializer.exclude(new String[] {
            "password"
        }).serialize(list));
        buff.append("}");
        jsonString = buff.toString();
        return "success";
	    }
}
